import { Body, Controller, Get, Post, Request, UploadedFile, UseGuards, UseInterceptors } from '@nestjs/common';
import { BaseService } from './base.service';
import { RegisterDto } from './dto/register-user.dto';
import { ApiTags, ApiBearerAuth, ApiOkResponse, ApiOperation, ApiBody } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { LoginSuccess, CurrentUserInfoDto, LoginDto } from './dto';
import { Public } from 'src/common/guards';
import { UsersDto } from 'src/db/dto';
import { CurrentUser } from 'src/common/paramDecorators';
import { getOneById } from 'src/utils';
import { InjectModel } from '@nestjs/mongoose';
import { Users, UsersDocument } from 'src/db/schemas/users.schema';
import { Model } from 'mongoose';
import { MenusService } from '../menus/menus.service';
import { getMeunsTree } from './fns/loop';
import { FileInterceptor } from '@nestjs/platform-express';
import { createWriteStream } from 'fs';
import { join } from 'lodash';

@ApiTags('基础接口')
@Controller()
@ApiBearerAuth('Authorization')
export class BaseController {
  constructor(
    public readonly baseService: BaseService,
    public readonly menusService: MenusService,
    @InjectModel(Users.name) private usersModel: Model<UsersDocument>,
  ) { }

  @Public()
  @Post('login')
  @ApiOperation({
    summary: '登录接口',
  })
  @ApiOkResponse({
    type: LoginSuccess
  })
  @ApiBody({
    type: LoginDto
  })
  @UseGuards(AuthGuard('local'))
  async login(
    @Request() res: {
      user: UsersDto
    }
  ) {
    return this.baseService.login(res.user);
  }

  @Public()
  @Post('register')
  @ApiOperation({
    summary: '注册接口',
  })
  @ApiOkResponse({
    type: LoginSuccess
  })
  async register(@Body() registerDto: RegisterDto) {
    return this.baseService.register(registerDto)
  }

  @Get('getCurrentUserInfo')
  @ApiOperation({
    summary: '获取当前用户信息',
  })
  @ApiOkResponse({
    type: CurrentUserInfoDto
  })
  async getCurrentUserInfo(@CurrentUser() currentUser: GolbalTypes.JWTUser) {
    const data = await this.usersModel.findById(currentUser._id, {
      'password': 0
    }).populate('role').exec()
    const newData: any = data.toJSON()
    let menus = []
    try {
      menus = await this.menusService.getMenusByIds(newData.role.limits);
    } catch (error) {

    }

    return {
      data: {
        ...newData,
        menus,
        menusTree: getMeunsTree(menus)
      }
    }
  }

}
